<?php

namespace common\models;

use Yii;
use yii\web\IdentityInterface;

/**
 * This is the model class for table "{{%admin}}".
 *
 * @property int $id ID
 * @property int $pid 父ID
 * @property string $path 路径, 例: -0-1-
 * @property string $invite_code 邀请码
 * @property string $username 用户名
 * @property string $password_hash 密码
 * @property string $email 邮箱
 * @property string $mobile 手机号
 * @property string $photo 头像
 * @property string $google_key MFA秘钥
 * @property string $auth_key COOKIE校验串
 * @property string $sso_key 单点校验串
 * @property string $access_token 访问令牌
 * @property int $status 状态: 0封停 1正常
 * @property string|null $deny_end_time 封停截止时间, Null:无期
 * @property int $group 管理组, 0:超管
 * @property string $user_preference 用户偏好
 * @property string $created_at
 * @property string|null $updated_at
 */
class Admin extends \builder\base\BaseActiveRecord implements IdentityInterface
{
    // 定义拥有者分组ID
    const ADMIN_GROUP = 0;

    // 定义系统书面称呼
    const SYSTEM_NAME = '当前系统';

    // 定义账户封停状态
    const STATUS_INACTIVE = 0;

    // 定义账户正常状态
    const STATUS_ACTIVE = 1;

    /**
     * 定义属性 - 重复密码
     * @var string
     */
    public $password_hash_repeat = '';

    /**
     * {@inheritdoc}
     */
    public static function tableName()
    {
        return '{{%admin}}';
    }

    /**
     * @param string $username 账号
     * @return static|null
     */
    public static function findByUsername($username)
    {
        return static::findOne(['username' => $username]);
    }

    /**
     * Summary of findIdentity
     * @param mixed $id
     * @return Admin|null
     */
    public static function findIdentity($id)
    {
        return static::findOne($id);
    }

    /**
     * Summary of findIdentityByAccessToken
     * @param mixed $token
     * @param mixed $type
     * @return Admin|null
     */
    public static function findIdentityByAccessToken($token, $type = null)
    {
        return static::findOne(['access_token' => $token]);
    }

    /**
     * {@inheritdoc}
     */
    public function getId()
    {
        return $this->getPrimaryKey();
    }

    /**
     * {@inheritdoc}
     */
    public function getAuthKey()
    {
        return $this->auth_key;
    }

    /**
     * {@inheritdoc}
     */
    public function validateAuthKey($authKey)
    {
        return $this->getAuthKey() === $authKey;
    }

    /**
     * Validates password
     *
     * @param string $password password to validate
     * @return bool if password provided is valid for current user
     */
    public function validatePassword($password)
    {
        return Yii::$app->security->validatePassword($password, $this->password_hash);
    }

    /**
     * Generates password hash from password and sets it to the model
     * @param string $password
     * @throws \yii\base\Exception
     */
    public function setPassword($password)
    {
        $this->password_hash = Yii::$app->security->generatePasswordHash($password);
    }

    /**
     * Generates "remember me" authentication key
     */
    public function setAuthKey()
    {
        $this->auth_key = Yii::$app->security->generateRandomString();
    }

    /**
     * 校验规则 - 用户名敏感字符验证
     * @param string $attribute
     * @param array $params
     */
    public function specialCharsValidate($attribute, $params)
    {
        $specialChar = [
            'admin', 'administrator', 'root', 'sys', 'system', '系统', '系统用户', '【无归属订单】',
        ];
        if (in_array($this->$attribute, $specialChar)) {
            $this->addError($attribute, "用户名 {$this->$attribute} 是敏感字符");
        }
    }

    /**
     * @return array
     */
    public function scenarios()
    {
        $scenarios = parent::scenarios();
        // 登录
        $scenarios['SCE_Admin_Login'] = ['username', 'password_hash'];
        // 新增
        $scenarios['SCE_Admin_Create'] = ['photo', 'username', 'password_hash', 'password_hash_repeat', 'email', 'mobile', 'group', 'path'];
        // 编辑
        $scenarios['SCE_Admin_Update'] = ['photo', 'username', 'password_hash', 'password_hash_repeat', 'email', 'mobile', 'status', 'deny_end_time', 'group'];
        // 账户设置
        $scenarios['SCE_Account_Setting'] = ['photo', 'password_hash', 'password_hash_repeat', 'email', 'mobile'];

        return $scenarios;
    }

    /**
     * {@inheritdoc}
     */
    public function rules()
    {
        return [
            [['path', 'invite_code', 'username', 'email', 'mobile', 'sso_key', 'access_token', 'group'], 'required'],
            [['password_hash'], 'required', 'on' => ['SCE_Admin_Login', 'SCE_Admin_Create']],
            [['username', 'password_hash'], 'trim'],
            [['username'], 'string', 'max' => 20],
            [['username'], 'match', 'pattern' => PHP_USERNAME_REGEX, 'message' => '账号只能包含数字、字母、汉字。'],
            [['username'], 'specialCharsValidate', 'on' => ['SCE_Admin_Create', 'SCE_Admin_Update']],
            [['username'], 'unique', 'except' => ['SCE_Admin_Login']],
            [['password_hash'], 'string', 'min' => 8, 'max' => 20],
            [['password_hash'], 'match', 'pattern' => PHP_PASSWORD_REGEX, 'message' => '密码必须包含英文字母、数字、特殊字符中的两种。'],
            [['password_hash'], 'compare', 'on' => ['SCE_Admin_Create', 'SCE_Admin_Update', 'SCE_Account_Setting']],
            [['pid', 'status', 'group'], 'integer'],
            [['status'], 'in', 'range' => [self::STATUS_ACTIVE, self::STATUS_INACTIVE]],
            [['status'], 'default', 'value' => self::STATUS_ACTIVE],
            [['path', 'invite_code', 'email', 'photo', 'auth_key', 'sso_key', 'access_token'], 'string', 'max' => 255],
            [['email'], 'email'],
            [['mobile'], 'string', 'length' => 11],
            [['mobile'], 'match', 'pattern' => PHP_MOBILE_REGEX, 'message' => '手机号格式不正确。'],
            [['google_key'], 'string', 'max' => 50],
            [['user_preference'], 'string', 'max' => 1000],
            [['deny_end_time', 'created_at', 'updated_at'], 'safe'],

        ];
    }

    /**
     * {@inheritdoc}
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'pid' => '父ID',
            'path' => '路径',
            'invite_code' => '邀请码',
            'username' => '账号',
            'password_hash' => '密码',
            'password_hash_repeat' => '重复密码',
            'email' => '邮箱',
            'mobile' => '手机号',
            'photo' => '头像',
            'google_key' => 'MFA秘钥',
            'auth_key' => 'COOKIE校验串',
            'sso_key' => '单点校验串',
            'access_token' => '访问令牌',
            'status' => '状态',
            'deny_end_time' => '封停截止时间',
            'group' => '管理组, 0:超管',
            'user_preference' => '用户偏好',
            'created_at' => '创建时间',
            'updated_at' => '更新时间',
        ];
    }
}
